package com.eduagent.xwqeduagent.service.lmpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.api.GeneralImageEditingApi;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.model.CreateImageSynthesisTaskRequest;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.model.CreateImageSynthesisTaskResponse;
import com.eduagent.xwqeduagent.api.PictureDoodlePainting.api.PictureDoodlePaintingApi;
import com.eduagent.xwqeduagent.api.PictureDoodlePainting.model.CreateDoodlePaintingTaskRequest;
import com.eduagent.xwqeduagent.api.PictureDoodlePainting.model.CreateDoodlePaintingTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunTextToImage.api.AliYunAiTextToImageApi;
import com.eduagent.xwqeduagent.api.aliyunTextToImage.model.CreateTextToImageTaskRequest;
import com.eduagent.xwqeduagent.api.aliyunTextToImage.model.CreateTextToImageTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunaiImageOutPaining.api.AliYunAiApi;
import com.eduagent.xwqeduagent.api.aliyunaiImageOutPaining.model.CreateOutPaintingTaskRequest;
import com.eduagent.xwqeduagent.api.aliyunaiImageOutPaining.model.CreateOutPaintingTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunaiReshapingImage.api.AliYunAiReshapingImageApi;
import com.eduagent.xwqeduagent.api.aliyunaiReshapingImage.model.CreateImageRestyleTaskRequest;
import com.eduagent.xwqeduagent.api.aliyunaiReshapingImage.model.CreateImageRestyleTaskResponse;
import com.eduagent.xwqeduagent.exception.BusinessException;
import com.eduagent.xwqeduagent.exception.ErrorCode;
import com.eduagent.xwqeduagent.exception.ThrowUtils;
import com.eduagent.xwqeduagent.model.dto.CreateDoodlePaintingRequest;
import com.eduagent.xwqeduagent.model.dto.CreateGeneralImageEditingRequest;
import com.eduagent.xwqeduagent.model.dto.CreatePictureOutPaintingTaskRequest;
import com.eduagent.xwqeduagent.model.dto.CreatePictureTextToImageTaskRequest;
import com.eduagent.xwqeduagent.model.dto.PortraitStyleRemakeRequest;
import com.eduagent.xwqeduagent.service.PictureService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.hutool.json.JSONUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class PictureServicelmpl implements PictureService {

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private AliYunAiTextToImageApi aliYunAiTextToImageApi;

    @Resource
    private AliYunAiReshapingImageApi aliYunAiReshapingImageApi;
    
    @Resource
    private GeneralImageEditingApi generalImageEditingApi;
    
    @Resource
    private PictureDoodlePaintingApi pictureDoodlePaintingApi;

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest) {
        ThrowUtils.throwIf(ObjectUtil.isEmpty(createPictureOutPaintingTaskRequest), ErrorCode.NOT_FOUND_ERROR);
        
        // 检查URL是否为空
        String imageUrl = createPictureOutPaintingTaskRequest.getUrl();
        ThrowUtils.throwIf(StrUtil.isBlank(imageUrl), ErrorCode.PARAMS_ERROR, "图片URL不能为空");
        
        // 确保URL格式正确（以http://或https://开头）
        if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://")) {
            imageUrl = "http://" + imageUrl;
        }
        
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        
        // 设置model
        taskRequest.setModel("image-out-painting");
        
        // 设置input
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(imageUrl);
        taskRequest.setInput(input);
        
        // 检查parameters是否为空
        CreateOutPaintingTaskRequest.Parameters parameters = createPictureOutPaintingTaskRequest.getParameters();
        if (parameters == null) {
            // 如果为空，创建一个默认的parameters对象
            parameters = new CreateOutPaintingTaskRequest.Parameters();
            // 设置一些默认值，例如小幅扩展图片
            parameters.setXScale(1.2f);  // 默认扩展20%
            parameters.setYScale(1.2f);
        } else {
            // 确保至少有一个有效的扩展参数
            boolean hasValidExtension = false;
            
            // 检查output_ratio是否有效
            if (parameters.getOutputRatio() != null && !parameters.getOutputRatio().isEmpty() && 
                    (parameters.getOutputRatio().equals("1:1") || parameters.getOutputRatio().equals("3:4") || 
                    parameters.getOutputRatio().equals("4:3") || parameters.getOutputRatio().equals("9:16") || 
                    parameters.getOutputRatio().equals("16:9"))) {
                hasValidExtension = true;
            }
            
            // 检查x_scale和y_scale是否有效
            if (parameters.getXScale() != null && parameters.getXScale() > 1.0f) {
                hasValidExtension = true;
            } else {
                parameters.setXScale(1.0f);  // 设为默认值
            }
            
            if (parameters.getYScale() != null && parameters.getYScale() > 1.0f) {
                hasValidExtension = true;
            } else {
                parameters.setYScale(1.0f);  // 设为默认值
            }
            
            // 检查offset参数是否有效
            if ((parameters.getTopOffset() != null && parameters.getTopOffset() > 0) || 
                    (parameters.getBottomOffset() != null && parameters.getBottomOffset() > 0) || 
                    (parameters.getLeftOffset() != null && parameters.getLeftOffset() > 0) || 
                    (parameters.getRightOffset() != null && parameters.getRightOffset() > 0)) {
                hasValidExtension = true;
            }
            
            // 如果没有任何有效的扩展参数，则设置默认的扩展
            if (!hasValidExtension) {
                parameters.setXScale(1.2f);  // 默认扩展20%
                parameters.setYScale(1.2f);
            }
            
            // 确保角度在有效范围内
            if (parameters.getAngle() == null || parameters.getAngle() < 0 || parameters.getAngle() > 359) {
                parameters.setAngle(0);
            }
        }
        
        taskRequest.setParameters(parameters);
        
        // 打印请求体，方便调试
        String requestBody = JSONUtil.toJsonStr(taskRequest);
        log.info("创建扩图任务请求体: {}", requestBody);
        
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    @Override
    public CreateTextToImageTaskResponse createTextToImageTask(CreatePictureTextToImageTaskRequest createPictureTextToImageTaskRequest) {
        // 参数校验
        ThrowUtils.throwIf(createPictureTextToImageTaskRequest == null, ErrorCode.NOT_FOUND_ERROR, "请求参数不能为空");

        // 构建请求参数
        CreateTextToImageTaskRequest taskRequest = new CreateTextToImageTaskRequest();
        taskRequest.setModel(createPictureTextToImageTaskRequest.getModel());

        // 设置输入参数
        CreateTextToImageTaskRequest.Input input = new CreateTextToImageTaskRequest.Input();
        input.setPrompt(createPictureTextToImageTaskRequest.getPrompt());
        input.setNegativePrompt(createPictureTextToImageTaskRequest.getNegativePrompt());
        taskRequest.setInput(input);

        // 设置任务参数
        CreateTextToImageTaskRequest.Parameters parameters = new CreateTextToImageTaskRequest.Parameters();
        parameters.setN(createPictureTextToImageTaskRequest.getN());
        parameters.setSize(createPictureTextToImageTaskRequest.getSize());
        parameters.setSeed(createPictureTextToImageTaskRequest.getSeed());
        parameters.setWatermark(true);
        parameters.setPromptExtend(true);
        taskRequest.setParameters(parameters);

        // 直接调用阿里云 API
        return aliYunAiTextToImageApi.createTextToImageTask(taskRequest);
    }

    @Override
    public CreateImageRestyleTaskResponse createImageRestyleTask(PortraitStyleRemakeRequest portraitStyleRemakeRequest) {
        // 参数校验
        ThrowUtils.throwIf(portraitStyleRemakeRequest == null, ErrorCode.NOT_FOUND_ERROR, "请求参数不能为空");

        // 构建请求参数
        CreateImageRestyleTaskRequest createImageRestyleTaskRequest = new CreateImageRestyleTaskRequest();
        createImageRestyleTaskRequest.setModel("wanx-style-repaint-v1");

        // 设置输入参数
        CreateImageRestyleTaskRequest.Input input = new CreateImageRestyleTaskRequest.Input();
        input.setImageUrl(portraitStyleRemakeRequest.getImageUrl());
        input.setStyleIndex(portraitStyleRemakeRequest.getStyleIndex());
        createImageRestyleTaskRequest.setInput(input);


        // 直接调用阿里云 API
        return aliYunAiReshapingImageApi.createImageRestyleTask(createImageRestyleTaskRequest);
    }

    @Override
    public CreateImageSynthesisTaskResponse createGeneralImageEditing(CreateGeneralImageEditingRequest createGeneralImageEditingRequest) {
        // 参数校验
        ThrowUtils.throwIf(createGeneralImageEditingRequest == null, ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        
        // 检查核心参数
        ThrowUtils.throwIf(StrUtil.isBlank(createGeneralImageEditingRequest.getFunction()), 
                ErrorCode.PARAMS_ERROR, "功能类型不能为空");
        ThrowUtils.throwIf(StrUtil.isBlank(createGeneralImageEditingRequest.getPrompt()), 
                ErrorCode.PARAMS_ERROR, "提示词不能为空");
        ThrowUtils.throwIf(StrUtil.isBlank(createGeneralImageEditingRequest.getBaseImageUrl()), 
                ErrorCode.PARAMS_ERROR, "输入图像URL不能为空");
                
        // 检查局部重绘时必须提供蒙版图像URL
        if ("description_edit_with_mask".equals(createGeneralImageEditingRequest.getFunction())) {
            ThrowUtils.throwIf(StrUtil.isBlank(createGeneralImageEditingRequest.getMaskImageUrl()), 
                    ErrorCode.PARAMS_ERROR, "局部重绘功能必须提供蒙版图像URL");
        }
        
        // 构建API请求参数
        CreateImageSynthesisTaskRequest taskRequest = new CreateImageSynthesisTaskRequest();
        taskRequest.setModel("wanx2.1-imageedit");
        
        // 设置输入参数
        CreateImageSynthesisTaskRequest.Input input = new CreateImageSynthesisTaskRequest.Input();
        input.setFunction(createGeneralImageEditingRequest.getFunction());
        input.setPrompt(createGeneralImageEditingRequest.getPrompt());
        input.setBaseImageUrl(createGeneralImageEditingRequest.getBaseImageUrl());
        
        // 只有在局部重绘功能时才设置maskImageUrl
        if ("description_edit_with_mask".equals(createGeneralImageEditingRequest.getFunction())) {
            input.setMaskImageUrl(createGeneralImageEditingRequest.getMaskImageUrl());
        }
        
        taskRequest.setInput(input);
        
        // 设置处理参数
        CreateImageSynthesisTaskRequest.Parameters parameters = new CreateImageSynthesisTaskRequest.Parameters();
        parameters.setN(createGeneralImageEditingRequest.getN());
        parameters.setSeed(createGeneralImageEditingRequest.getSeed());
        parameters.setWatermark(createGeneralImageEditingRequest.getWatermark());
        taskRequest.setParameters(parameters);
        
        // 打印请求体，方便调试
        String requestBody = JSONUtil.toJsonStr(taskRequest);
        log.info("创建通用图像编辑任务请求体: {}", requestBody);
        
        // 调用API
        return generalImageEditingApi.createImageSynthesisTask(taskRequest);
    }

    @Override
    public CreateDoodlePaintingTaskResponse createDoodlePaintingTask(CreateDoodlePaintingRequest createDoodlePaintingRequest) {
        // 参数校验
        ThrowUtils.throwIf(createDoodlePaintingRequest == null, ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        
        // 核心参数校验
        ThrowUtils.throwIf(StrUtil.isBlank(createDoodlePaintingRequest.getPrompt()), 
                ErrorCode.PARAMS_ERROR, "提示词不能为空");
        ThrowUtils.throwIf(StrUtil.isBlank(createDoodlePaintingRequest.getSketchImageUrl()), 
                ErrorCode.PARAMS_ERROR, "线稿图像URL不能为空");
                
        String sketchUrl = createDoodlePaintingRequest.getSketchImageUrl();
        // 打印草图URL，便于调试
        log.info("线稿生图的草图URL: {}", sketchUrl);
        
        // 确保URL格式正确（以http://或https://开头）
        if (!sketchUrl.startsWith("http://") && !sketchUrl.startsWith("https://")) {
            sketchUrl = "https://" + sketchUrl;
        }
        
        // 构建API请求参数
        CreateDoodlePaintingTaskRequest taskRequest = new CreateDoodlePaintingTaskRequest();
        taskRequest.setModel("wanx-sketch-to-image-lite");
        
        // 设置输入参数
        CreateDoodlePaintingTaskRequest.Input input = new CreateDoodlePaintingTaskRequest.Input();
        input.setPrompt(createDoodlePaintingRequest.getPrompt());
        input.setSketchImageUrl(sketchUrl); // 使用处理后的URL
        taskRequest.setInput(input);
        
        // 设置处理参数
        CreateDoodlePaintingTaskRequest.Parameters parameters = new CreateDoodlePaintingTaskRequest.Parameters();
        parameters.setStyle(createDoodlePaintingRequest.getStyle());
        parameters.setSize(createDoodlePaintingRequest.getSize());
        parameters.setN(createDoodlePaintingRequest.getN());
        parameters.setSketchWeight(createDoodlePaintingRequest.getSketchWeight());
        parameters.setSketchExtraction(createDoodlePaintingRequest.getSketchExtraction());
        parameters.setSketchColor(createDoodlePaintingRequest.getSketchColor());
        taskRequest.setParameters(parameters);
        
        // 打印请求体，方便调试
        String requestBody = JSONUtil.toJsonStr(taskRequest);
        log.info("创建线稿生图任务请求体: {}", requestBody);
        
        // 调用API
        return pictureDoodlePaintingApi.createDoodlePaintingTask(taskRequest);
    }
}
